package com.cans.ssoserver.web.system;

import com.cans.base.dto.PageRes;
import com.cans.base.dto.ResDto;
import com.cans.ssoserver.model.system.SystemModel;
import com.cans.ssoserver.service.system.api.ISystemService;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;

/**
 * description: 系统接入WEB层
 *
 * @author cans
 * @date 2018/7/30
 */
@Controller
@RequestMapping("/system")
public class SystemController {

    @Resource
    private ISystemService systemService;

    /**
     * 去分页列表
     * @return
     */
    @GetMapping("/toPageList")
    public String toPageList(){

        return "system/systemList";
    }

    /**
     * 去添加
     * @return
     */
    @GetMapping("/toAdd")
    public String toAdd(){

        return "system/systemAdd";
    }

    /**
     * 去修改
     * @return
     */
    @GetMapping("/toUpdate")
    public String toUpdate(){

        return "system/systemUpdate";
    }

    /**
     * 去查看
     * @return
     */
    @GetMapping("/view")
    public String view(){

        return "system/systemView";
    }

    /**
     * 分页查询
     * @return
     */
    @GetMapping("/pageList")
    @ResponseBody
    public PageRes pageList(Integer page, Integer limit,String systemName){

        Sort sort = new Sort(Sort.Direction.ASC,"systemIndex");
        Pageable pageable = new PageRequest(page - 1,limit,sort);

        return systemService.findAll((root, criteriaQuery, criteriaBuilder) -> {

            List<Predicate> list = new ArrayList<>();
            if (!StringUtils.isEmpty(systemName)) {
                list.add(criteriaBuilder.like(root.get("systemName"), "%" + systemName + "%"));
            }

            return criteriaBuilder.and(list.toArray(new Predicate[0]));
        },pageable);
    }


    /**
     * 新增系统
     * @param systemModel
     * @return
     */
    @PostMapping("/add")
    @ResponseBody
    public ResDto add(SystemModel systemModel){

        systemService.save(systemModel);

        return ResDto.success();
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @DeleteMapping(value = "/delete/{id}")
    @ResponseBody
    public ResDto delete(@PathVariable String id){

        systemService.delete(id);

        return ResDto.success();
    }
}
